package top.raoqq.sky.handler;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.raoqq.sky.exception.BizException;
import top.raoqq.sky.vo.Result;

/**
 * 全局异常处理器
 * @author 饶奇奇
 * @date 2023/8/7
 */
@Component
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BizException.class)
    public Result<Void> handler(BizException ex) {
        return Result.ajax(ex.getReason());
    }


    @ExceptionHandler(BindException.class)
    public Result<Void> handler(BindException ex) {
        String errorMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fair(errorMsg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handler(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fair(errorMsg);
    }
}
